﻿using System;
using System.Linq;
using System.Net;
using System.Text;
using Enyim.Caching;
using Ayatta.Contract;
using System.Net.Mail;
using ServiceStack.Text;
using Web.Base.Security;
using System.Web.Security;
using Web.Base.Controllers;
using System.Configuration;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extensions;

namespace Web.Passport.Controllers
{
    public class PassportBaseController : BaseController
    {
        protected static readonly string AesKey = ConfigurationManager.AppSettings["Aes.Key"];
        protected static readonly string PasswordSalt = ConfigurationManager.AppSettings["Password.Salt"];

        public PassportBaseController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient) : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        protected void SetAuthCookie(string userName, bool createPersistentCookie, Identity identity)
        {
            var ip = GetIpAddress();
            PassportService.UpdateUserLastLoginInfo(identity.Id,ip);
            var userData = JsonSerializer.SerializeToString(identity);
            var authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);
            var ticket = FormsAuthentication.Decrypt(authCookie.Value);
            var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
            authCookie.Value = FormsAuthentication.Encrypt(newTicket);
            if (createPersistentCookie)
            {
                authCookie.Expires = DateTime.Now.AddDays(14);
            }
            Response.Cookies.Add(authCookie);
        }

        protected void Register(RegisterLog log, dynamic data)
        {
            ExtraService.CreateRegisterLog(log);
            //var mails = MemcachedClient.Put(CacheKey.Base.EmailAccount, BaseService.GetAllEmailAccount);
            //var templates = MemcachedClient.Put(CacheKey.Base.EmailTemplate, BaseService.GetAllEmailTemplate);
            //var mail = mails.FirstOrDefault(o => o.Status && o.Category == EmailAccountCategory.Register);
            //var template = templates.FirstOrDefault(o => o.Id == 1);
            //if (template != null)
            //{
            //    var tpl = template.Body;
            //    template.Body = GetResult(data, tpl);
            //    SendEmail(log, mail, template);
            //}
        }

        private static void SendEmail(RegisterLog log, EmailAccount mail, EmailTemplate template)
        {
            var from = new MailAddress(mail.Email, mail.DisplayName);
            var to = new MailAddress(log.UserName);

            using (var client = new SmtpClient(mail.Host, mail.Port))
            using (var message = new MailMessage(from, to))
            {
                message.IsBodyHtml = true;
                message.Priority = MailPriority.High;

                if (!string.IsNullOrEmpty(template.BccEmailAddresses))
                {
                    foreach (var o in template.BccEmailAddresses.Split(',').Where(o => o.IsEmail()))
                    {
                        message.Bcc.Add(o);
                    }
                }
                message.Subject = template.Subject;
                message.SubjectEncoding = Encoding.UTF8;

                message.Body = template.Body;
                message.BodyEncoding = Encoding.UTF8;

                client.EnableSsl = mail.EnableSsl;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = mail.UseDefaultCredentials;
                client.Credentials = new NetworkCredential(mail.Username, mail.Password);
                client.Send(message);
            }
        }

        private static string GetResult(dynamic data, string template)
        {
            if (data == null)
            {
                return template;
            }
            if (!string.IsNullOrEmpty(template))
            {
                //using (var service = new TemplateService())
                //{
                //    return service.Parse(template, data);
                //}
            }
            return string.Empty;
        }
    }
}
